<template>
  <div class="my-goods-list">
    <h3>商品列表</h3>
    <MyTable :goodsList="goodsList">
      <template #thead>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #tbody="{item, index}">
        <td>{{ index + 1 }}</td>
        <td>{{ item.goods_name }}</td>
        <td>{{ item.goods_price | price }}</td>
        <td>
          <input
            v-if="item.inputVisible"
            class="tag-input form-control"
            type="text"
            v-focus
            @blur="item.inputVisible = false"
            @keyup.enter="addTag(item, $event)"
            @keyup.esc="$event.target.value = ''"
          />
          <button
            v-else
            class="btn btn-primary btn-sm add-tag"
            @click="item.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="tag in item.tags"
            :key="tag"
            class="badge badge-warning"
            >{{ tag }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(item.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import axios from 'axios'
import MyTable from '../components/MyTable'
export default {
  filters: {
    price (value) {
      return '￥ ' + value.toFixed(2)
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      },
    },
  },
  components: {
    MyTable,
  },
  data() {
    return {
      goodsList: [],
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      const res = await axios({
        method: 'get',
        url: 'https://www.escook.cn/api/goods',
      })
      if (res.status === 200) {
        this.goodsList = res.data.data
      } else {
        console.error('获取商品列表失败')
      }
    },
    del(id) {
      this.goodsList = this.goodsList.filter(item => item.id !== id)
    },
    addTag(item, e) {
      if (!e.target.value.trim()) return alert('请输入内容')
      item.tags.push(e.target.value)
      item.inputVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.my-goods-list {
  .badge {
    margin-right: 5px;
  }
  .add-tag {
    margin-right: 5px;
  }
}
</style>
